<template>
  <canvas style="width: 100%;height: 100%" v-if="showCanvas" :id="pagId"/>
</template>

<script setup>
import {PAGInit} from 'libpag'
import axios from 'axios'
import { IndexedDB } from '@kieranwv/utils'
defineOptions({name: 'PAGAnimationView'})
import {useId} from 'vue'
const props = defineProps({
  path: {
    type: String,
    default: './'
  },
  name: {
    type: String,
    default: 'excuse'
  }
})
const emit = defineEmits(['rendered'])
let PAGInstance
let PAGViewInstance
PAGInit().then((PAG) => {
  PAGInstance = PAG
})
const showCanvas = ref(true)
const request = axios.create()
const db = new IndexedDB()
const pagId = computed(() => `pag-${useId()}`)

const pagFileUrl = computed(() => {
  return `${props.path}/${props.name}.pag`
})

async function loadPagFile() {
  const _cache = await db.find(props.name)
  if (
      _cache
      && _cache.value
      && _cache.version === props.version
  ) {
    await renderPagFile(_cache.value)
  } else {
    request(pagFileUrl.value, {responseType: 'blob'})
        .then(response => response.data)
        .then(async (blob) => {
          const file = new window.File([blob], pagFileUrl.value.replace(/(.*\/)*([^.]+)/, '$2'))
          db.insert(props.name, {
            value: file,
            label: props.name,
            timestamp: new Date().getTime(),
            version: props.version,
          })
          await renderPagFile(file)
        })
  }
}

async function renderPagFile(file) {
  if (!PAGInstance) {
    PAGInstance = await PAGInit()
  }
  try {
    const pagFile = await PAGInstance.PAGFile.load(file)
    if (!pagFile) {
      throw new Error('pagFile is null')
    }
    /*const dom = document.getElementById(pagId.value)
    if (!dom) {
      throw new Error('dom is null')
    }
    dom.width = pagFile.width()
    dom.height = pagFile.height()*/
    PAGViewInstance = await PAGInstance.PAGView.init(pagFile, `#${pagId.value}`)
    if (!PAGViewInstance) {
      throw new Error('PAGViewInstance is null')
    }
    PAGViewInstance.setRepeatCount(0)
    await PAGViewInstance.play()
    emit('rendered')
  } catch (e) {
    console.error('[PAGAnimation.vue] error: ', e)
  }
}

function play() {
  showCanvas.value = true
  if (PAGViewInstance && !PAGViewInstance.isDestroyed) {
    PAGViewInstance.play()
  } else {
    loadPagFile()
  }
}

function stop() {
  if (PAGViewInstance && !PAGViewInstance.isDestroyed) {
    PAGViewInstance.stop()
  }
}

function destroy() {
  if (PAGViewInstance && !PAGViewInstance.isDestroyed) {
    PAGViewInstance.destroy()
    showCanvas.value = false
  }
}

defineExpose({
  play,
  stop,
  destroy,
  id: pagId.value,
})
onMounted(() => {
  play()
})
onUnmounted(() => {
  destroy()
})
</script>
